<template>
  <n-card :bordered="false" class="mt-3">
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.userID"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
      :striped="true"
    >
      <template #tableTitle>
        <n-button type="primary" @click="addTable">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建用户
        </n-button>
      </template>
    </BasicTable>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新建用户">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="用户名" path="username">
          <n-input placeholder="请输入用户名" v-model:value="formParams.username" />
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input type="password" placeholder="请输入密码" v-model:value="formParams.password" />
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input placeholder="请输入邮箱" v-model:value="formParams.email" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { columns } from './columns';
import type { UserItem } from './types';
import { PlusOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { type FormRules } from 'naive-ui';
import { UserProfileApi } from '@/api/new/userProfleApi';
import { AdminManagementApi } from '@/api/new/AdminManagementApi';
import { useMessage } from 'naive-ui';

const message = useMessage();
const router = useRouter();

const rules: FormRules = {
  username: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入用户名',
  },
  password: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入密码',
  },
  email: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入邮箱',
  },
};

const formRef: any = ref(null);
const actionRef = ref();

const showModal = ref(false);
const formBtnLoading = ref(false);
const formParams = reactive({
  username: '',
  password: '',
  email: '',
});

const actionColumn = reactive({
  width: 120,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '封禁',
          onClick: () => {
            AdminManagementApi.banUser(record.userID).then(() => {
              message.success('封禁成功');
              reloadTable();
            }).catch((error) => {
              message.error(error?.message || '封禁失败');
            });
          },
          ifShow: () => {
            return record.status === 'normal';
          },
        }
      ],
    });
  },
});

const loadDataTable = async (res) => {
  try {
    const response = await AdminManagementApi.getUserList(res.page, res.pageSize);
    const parsedData = JSON.parse(response);
    
    return {
      list: parsedData.data,
      itemCount: parsedData.total || 0,
      page: parsedData.pageNum,
      pageSize: parsedData.pageSize,
      pageCount: Math.ceil((parsedData.total || 0) / parsedData.pageSize)
    };
  } catch (error: any) {
    message.error(error?.message || '获取用户列表失败');
    return {
      list: [],
      itemCount: 0,
      page: res.page,
      pageSize: res.pageSize,
      pageCount: 0
    };
  }
};

function onCheckedRow(rowKeys) {
  console.log('选中的行:', rowKeys);
}

function reloadTable() {
  actionRef.value?.reload();
}

async function confirmForm() {
  formBtnLoading.value = true;
  try {
    await formRef.value?.validate();
    await UserProfileApi.register(
      formParams.username,
      formParams.password,
      formParams.email,
      ''
    );
    message.success('创建用户成功');
    showModal.value = false;
    reloadTable();
  } catch (error: any) {
    message.error(error?.message || '创建用户失败');
  } finally {
    formBtnLoading.value = false;
  }
}

function handleEdit(record: UserItem) {
  console.log('点击了编辑', record);
  router.push({ name: 'basic-info', params: { id: record.userID } });
}

function handleDelete(record: UserItem) {
  console.log('点击了删除', record);
  window['$message'].info('点击了删除');
}

function addTable() {
  showModal.value = true;
}
</script>

<style lang="less" scoped></style>
